package com.lingxu.base.system.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.util.ObjectConvertUtils;
import com.lingxu.base.common.util.Sm2Util;
import com.lingxu.base.common.util.UUID32Generator;
import com.lingxu.base.common.util.encrypt.MD5Utils;
import com.lingxu.base.system.manage.entity.SysUser;
import com.lingxu.base.system.manage.entity.TSysUser;
import com.lingxu.base.system.manage.mapper.SysUserMapper;
import com.lingxu.base.system.manage.model.UserParamDto;
import com.lingxu.base.system.manage.service.ISysUserService;
import com.lingxu.base.system.manage.vo.LoginUser;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description: 用户信息
 * @Author: LingXu
 * @Date:   2021-01-04
 * @Version: V1.0.1
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Resource
    private SysUserMapper sysUserMapper;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 用户信息-分页列表查询
     * @param page 分页信息
     * @param sysuser 用户信息
     * @return 用户信息列表
     */
    @Override
    public IPage<SysUser> queryPageList(Page<SysUser> page, SysUser sysuser){
        return sysUserMapper.queryList(page,sysuser);
    }

    /**
     * 用户信息-列表查询
     * @param sysuser 用户信息
     * @return 用户信息列表
     */
    @Override
    public List<SysUser> queryList(SysUser sysuser){
        return sysUserMapper.queryList(sysuser);
    }

    @Override
    public List<SysUser> getRoleUserList(String roleId, Integer flag) {
        return sysUserMapper.getRoleUserList(roleId,flag);
    }

    /**
     * 根据用户名查询用户信息
     * @param userName 用户名
     * @return 用户信息
     */
    @Override
    public SysUser getByName(String userName,String flag) {
        return sysUserMapper.getByName(userName,flag);
    }




    @Override
    public Result<?> updatePassword(String userName, String oldPassword, String newPassword, String confirmPassword) {
        SysUser user = sysUserMapper.getByName(userName,"1");
        String userpassword = user.getPassword();
        String userpasswordnew= MD5Utils.Md5Encrypt(oldPassword);

        if (!userpasswordnew.equals(userpassword)) {
            return Result.error("旧密码输入错误!");
        }
        if (ObjectConvertUtils.isEmpty(newPassword)) {
            return Result.error("新密码不允许为空!");
        }
        if (!newPassword.equals(confirmPassword)) {
            return Result.error("两次输入密码不一致!");
        }
        String password = MD5Utils.Md5Encrypt(newPassword);
        SysUser userNow=new SysUser();
        userNow.setPassword(password);
        userNow.setLastupdpwdtime(new Date());
        this.sysUserMapper.update(userNow, new LambdaQueryWrapper<SysUser>().eq(SysUser::getId, user.getId()));

        //推送T_SYS_USER
        sysUserMapper.updateTSysUser(user.getId(),password);
        return Result.ok("密码修改成功!");
    }


    @Override
    public Result<?> getOneById(String userId) {
        try {
            SysUser sysUser = sysUserMapper.selectById(userId);
            return Result.ok(sysUser,"查询成功");
        }catch (Exception e){
            logger.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    @Override
    public Result<?> queryByDeptid(String deptid) {
        List<SysUser> list = sysUserMapper.queryByDeptid(deptid);
        return Result.ok(list);
    }

    @Override
    public List<SysUser> queryListByDeptid(String deptid) {
        return sysUserMapper.queryByDeptid(deptid);
    }

    @Override
    @Transactional
    public Result<?> addOne(UserParamDto dto) {
        //用户信息保存
        SysUser maybeHaving= this.getByName(dto.getUserName(),"1");
        if(maybeHaving!=null){
            return Result.error("用户账号已存在");
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(dto,sysUser);
        if (StringUtils.isBlank(dto.getPassword())){
            sysUser.setPassword("123@Abcd");
        }
        Date date = new Date();
        String id = UUID32Generator.generate();

        String passwordEncode = Sm2Util.encrypt(sysUser.getPassword());
        sysUser.setPassword(passwordEncode);
        sysUser.setIsdel("0");
        sysUser.setCreatetime(date);
        sysUser.setId(id);
        sysUser.setLastupdpwdtime(date);
        this.save(sysUser);
        return Result.ok("添加成功");
    }
//    @Override
//    @Transactional
//    public Result<?> addOne(UserParamDto dto) {
//        //用户信息保存
//        SysUser maybeHaving= this.getByName(dto.getUserName(),"1");
//        if(maybeHaving!=null){
//            return Result.error("用户账号已存在");
//        }
//        SysUser sysUser = new SysUser();
//        BeanUtils.copyProperties(dto,sysUser);
//        if (StringUtils.isBlank(dto.getPassword())){
//            sysUser.setPassword("123@Abcd");
//        }
//        Date date = new Date();
//        String id = UUID32Generator.generate();
//        String salt = ObjectConvertUtils.randomGen(8);
//        String passwordEncode = PasswordUtil.encrypt(dto.getUserName(), dto.getPassword(), salt);
//        sysUser.setPassword(passwordEncode);
//        sysUser.setSalt(salt);
//        sysUser.setIsdel("0");
//        sysUser.setCreatetime(date);
//        sysUser.setId(id);
//        sysUser.setLastupdpwdtime(date);
//        this.save(sysUser);
//        return Result.ok("添加成功");
//    }
        @Override
        @Transactional
        public Result<?> editOne(UserParamDto dto){
            LoginUser userNow = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            Date date = new Date();
            SysUser sysUser = new SysUser();
            BeanUtils.copyProperties(dto,sysUser);
            //以下字段不可以被修改
            sysUser.setUsername(null);
            sysUser.setPassword(null);
            this.updateById(sysUser);
            return Result.ok("编辑成功");
        }
//    @Override
//    @Transactional
//    public Result<?> editOne(UserParamDto dto){
//        LoginUser userNow = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        Date date = new Date();
//        SysUser sysUser = new SysUser();
//        BeanUtils.copyProperties(dto,sysUser);
//        //以下字段不可以被修改
//        sysUser.setUsername(null);
//        sysUser.setPassword(null);
//        sysUser.setSalt(null);
//        this.updateById(sysUser);
//        return Result.ok("编辑成功");
//    }

    @Override
    @Transactional
    public Result<?> edit(SysUser sysUser){
        //以下字段不可以被修改
        sysUser.setUsername(null);
        sysUser.setPassword(null);
        this.updateById(sysUser);
        return Result.ok("编辑成功");
    }

    @Override
    public Result<?> deleteBatch(List<String> idList,String content){
        boolean flag = super.removeByIds(idList);
        if(flag){
            sysUserMapper.deleteTUserByIds(idList);
            return Result.ok(content);
        }else{
            return Result.ok(content);
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description 一周内未修改密码提示
     * @Date 2022/4/12 16:17
     * @Param: userId
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findNotModifyPassWordByWeek(String userId) {
        try {
            Integer i = sysUserMapper.findNotModifyPassWordByWeek(userId);
            if(i > 0){
                return Result.error("您已超过一周未修改密码，请及时修改密码！");
            }
            return Result.ok();
        }catch (Exception e){
            log.error("查询异常",e);
            return Result.error("查询异常");
        }
    }


//    /**
//     * @Author ysj闫世杰
//     * @Description 强制修改密码
//     * @Date 2022/7/6 15:30
//     * @Param: userId
//     * @return com.lingxu.base.common.api.vo.Result
//     **/
//    @Override
//    public Result findDefaultPwd(String userId) {
//        try {
//            SysUser sysUser = sysUserMapper.selectById(userId);
//            String def1 = "123@Abcd";
//            String def2 = "123";
//            String salt = sysUser.getSalt();
//            String pwd = sysUser.getPassword();
//            String passwordEncode1 = PasswordUtil.encrypt(sysUser.getUsername(), def1, salt);
//            String passwordEncode2 = PasswordUtil.encrypt(sysUser.getUsername(), def2, salt);
//            if(pwd.equals(passwordEncode1) || pwd.equals(passwordEncode2)){
//                return Result.error(505,"强制修改密码提醒");
//            }
//            return Result.ok();
//        }catch (Exception e){
//            logger.error("数据查询异常",e);
//            return Result.error("查询异常");
//        }
//    }

    @Override
    public void updateIsUse(String id, String isuse) {
        sysUserMapper.updateIsUse(id,isuse);
    }

    @Override
    public String findRoleId(String id) {
        return sysUserMapper.findRoleId(id);
    }

    @Override
    public void insertTSysUser(TSysUser tSysUser) {
        try {
            sysUserMapper.insertTSysUser(tSysUser);
        }catch (Exception e){
            logger.error("操作异常",e);
        }
    }


    @Override
    public void deleteUserByName(String ename) {
        try {
            sysUserMapper.deleteUser(ename);
            sysUserMapper.deleteTUser(ename);
        }catch (Exception e){
            logger.error("操作异常",e);

        }
    }


    @Override
    public void updateTSysUser(String id, String passwordEncode) {
        sysUserMapper.updateTSysUser(id,passwordEncode);
    }

    @Override
    public Integer findExistModelsOrData(String userId) {
        return  sysUserMapper.findExistModelsOrData(userId);
    }
}
